//
//  NewsListViewController.m
//  coba-iOS
//
//  Created by 郭四虎 on 15/12/9.
//  Copyright © 2015年 YouKu. All rights reserved.
//

#import "NewsListViewController.h"
#import "NewsModel.h"
#import "NewsListCell.h"
#import "ArticleListCell.h"
#import "ThirdImaCell.h"

static const NSInteger pageSize = 10;
static const NSInteger downPageSize = 5;
typedef enum{
    upPush = 0,
    downPush
} type;

@interface NewsListViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    NSMutableArray *_cacheArr;
    UILabel *_msgLb;
    NSMutableArray *_showDataArray;
    
    BOOL _isArticle;
}

@end

@implementation NewsListViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshTable) name:@"FailToReceive" object:nil];
    
    _cacheArr = [NSMutableArray array];
    self.dataArr = [NSMutableArray array];
    self.next_key = 0;
    
    CGRect rect = self.view.bounds;
    rect.size.height -= 60;
    
    self.view.frame = rect;
    
    if ([self.title isEqualToString:@"美文"]) {
        _isArticle = YES;
    }
    
    [self initUI];

}

- (void)refreshTable
{
    [self.tableView reloadData];
}

- (void)initUI
{
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64- 48) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15);
//    self.tableView.layer.borderColor = [UIColor lightGrayColor].CGColor;
//    self.tableView.layer.borderWidth = 1;
    
    [self.view addSubview:self.tableView];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ArticleListCell" bundle:nil] forCellReuseIdentifier:@"ArticleListCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"NewsListCell" bundle:nil] forCellReuseIdentifier:@"NewsListCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ThirdImaCell" bundle:nil] forCellReuseIdentifier:@"ThirdImaCell"];
    
    [self.tableView delsetExtraline];
    
    if (![ISBUS boolValue]) {
        self.tableView.header =[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
        self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getOtherNewData)];
    }else{
        self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getBusNewData)];
    }
}
#pragma mark @"下拉"
- (void)refresh
{
    NSString *max_id;
    if (self.dataArr.count) {
        NewsModel *model = self.dataArr[0];
        
        max_id = model.newsid;
    }
    if (!max_id) {
        
        [self getNotBusNewData];
        return;
    }
    NSLog(@"%@",max_id);
    NSDictionary *parameter = @{@"dir_name":_model.sortid,@"max_id":max_id,@"limit_num":@(downPageSize)};
    
    [self notBusPostwithPrameter:parameter dataArr:^(NSArray *arr) {
        
        NSArray *newArr = [self getNewModel:arr withType:downPush];
        
        NSRange range = NSMakeRange(0, [newArr count]);
        
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
        
        if (newArr.count) {
            [self.dataArr insertObjects:newArr atIndexes:indexSet];
        }else{
            [self.view performSelector:@selector(Message:) withObject:@"已是最新数据" afterDelay:0.5];
        }
        
        
        [[EGOCache globalCache]setObject:self.dataArr forKey:[NSString stringWithFormat:@"%@newsList",_model.sortid]withTimeoutInterval:86400*30];
        
        [self addADtoList];
        [_tableView reloadData];
    } error:^(NSError *err) {
        
    }];
    
}

- (void)addADtoList
{
    _showDataArray = [NSMutableArray arrayWithArray:self.dataArr];
    NSInteger num = 0;
    for (NSInteger i = 1; i<=self.dataArr.count; i++) {
        if (!(i%5)) {
            
            [_showDataArray insertObject:@"ad" atIndex:i+num];
            num++;
        }
    }
}

- (void)post:(NSString *)url back:(void(^)(NSError *))back
{

     NSDictionary *parameter = @{@"dir_name":_model.sortid,@"next_key":@(self.next_key),@"page_size":@(pageSize)};
    
    [MyAFN POST:url parameters:parameter block:^(id responseObject) {
        
        NSDictionary *response = responseObject;
        
        if ([[response objectForKey:@"status"]integerValue]) {
            
            if ([[response objectForKey:@"next_key"]integerValue]) {
                self.next_key = [[response objectForKey:@"next_key"] integerValue];
            }else{
                self.next_key = 1000;
            }
            
            
            for (NSDictionary *dic in [response objectForKey:@"newsList"]) {
                
                NewsModel *model = [[NewsModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                [self.dataArr addObject:model];
            }
        }
        
        if (self.dataArr.count == 0) {
            [self showMessage];
        }else{
            [self hideMessage];
            [self addADtoList];
            [_tableView reloadData];
        }
        
        [_tableView.footer endRefreshing];
        [_tableView.header endRefreshing];
        
    } error:^(NSError *error) {
        
        back(error);
        [_tableView.footer endRefreshing];
        [_tableView.header endRefreshing];
    } fromController:self];
}

- (void)notBusPostwithPrameter:(NSDictionary *)parameter dataArr:(void(^)(NSArray *))dataArr error:(void(^)(NSError *))err
{
    [MyAFN POST:NEWSLIST parameters:parameter block:^(id responseObject) {
        
        NSDictionary *response = responseObject;
        
        if ([[response objectForKey:@"status"]integerValue]) {
            
            NSMutableArray *arr = [NSMutableArray array];
            for (NSDictionary *dic in [response objectForKey:@"newsList"]) {
                
                NewsModel *model = [[NewsModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                [arr addObject:model];
            }
            
            [_tableView.footer endRefreshing];
            [_tableView.header endRefreshing];
            
            dataArr(arr);
        }
    } error:^(NSError *error) {
        [_tableView.footer endRefreshing];
        [_tableView.header endRefreshing];
        
        err(error);
    } fromController:self];
}

- (NSArray *)getNewModel:(NSArray *)newArr withType:(type)type
{
    NSArray *cacheArr = (NSArray *)[[EGOCache globalCache]objectForKey:[NSString stringWithFormat:@"%@newsList",_model.sortid]];
    
    NSMutableArray *tmpArr = [NSMutableArray arrayWithArray:newArr];
    
    NSInteger num = 0;
    if (cacheArr.count > pageSize) {
        num = pageSize;
    }else{
        num = cacheArr.count;
    }
    
    if (type == upPush) {
        
        for (int i = 0; i<num; i++) {
            NewsModel *cacheModel = cacheArr[cacheArr.count-1 - i];
            
            for (NewsModel *newModel in newArr) {
                
                if ([newModel.newsid isEqualToString:cacheModel.newsid]) {
                    [tmpArr removeObject:newModel];
                    break;
                }
            }
        }
        
    }else{
        
        for (int i = 0; i<num; i++) {
            NewsModel *cacheModel = cacheArr[i];
            
            for (NewsModel *newModel in newArr) {
                
                if ([newModel.newsid isEqualToString:cacheModel.newsid]) {
                    
                    [tmpArr removeObject:newModel];
                    break;
                }
            }
        }

    }
    
    return tmpArr;
}
#pragma mark @"入口"
- (void)createData
{
    self.width = WIDTH-20;
    
    self.bannerView.x = 10;
    self.bannerView2.x = 10;
    self.bannerView.y = 5;
    self.bannerView2.y = 5;
    [self ceateContentData];
    [self creatHeader];
}

- (void)ceateContentData
{
    if ([ISBUS boolValue]) {
        
        [self getBusNewData];
        
    }else{
        [self getNotBusNewData];
    }
}

-(void)creatHeader
{
    [[MyAd sharedMyad]headerViewwithTag:self.adkey target:self back:^(UIView *headView,NSArray *dataArr,bool iserror) {
        if (headView) {
            
            self.tableView.tableHeaderView = headView;
            _msgLb.frame = CGRectMake(20, SCALEY*(179)+20, WIDTH - 40, 50);
            self.scrollView = (SDCycleScrollView *)headView;
            self.adArr = dataArr;
            self.collectAd(self.scrollView,self.adArr,iserror);
            self.scrollView.shouldGetoffset = YES;

        }
        
    }];
}

- (void)getNotBusNewData
{
    NSArray *cacheArray = [NSArray array];
    if ([[EGOCache globalCache]objectForKey:[NSString stringWithFormat:@"%@newsList",_model.sortid]]) {
        
        cacheArray = (NSArray *)[[EGOCache globalCache]objectForKey:[NSString stringWithFormat:@"%@newsList",_model.sortid]];
        
    }
    
    NSDictionary *parameter = @{@"dir_name":_model.sortid,@"first_flag":@(0),@"page_size":@(pageSize)};
    
    [self notBusPostwithPrameter:parameter dataArr:^(NSArray *arr) {
        
        self.dataArr.array = [self getNewModel:arr withType:downPush];
        [self.dataArr addObjectsFromArray:cacheArray];
        [[EGOCache globalCache]setObject:self.dataArr forKey:[NSString stringWithFormat:@"%@newsList",_model.sortid]withTimeoutInterval:86400*30];
        [self addADtoList];
        [_tableView reloadData];
        
    } error:^(NSError *err) {
        
        self.dataArr.array = cacheArray;
        [self addADtoList];
        [_tableView reloadData];
    }];
}

- (void)getBusNewData
{
    if (self.next_key == 1000) {
        [self.view Message:@"亲,已经到底了" HiddenAfterDelay:1];
        [_tableView.footer endRefreshing];
        return;
    }
    
    [self post:[self getURL] back:^(NSError *error) {
        
        
    }];
}
#pragma mark @"上拉"
- (void)getOtherNewData
{
    NSString *min_id;
    if (self.dataArr.count) {
        NewsModel *model = self.dataArr[self.dataArr.count-1];
        
        min_id = model.newsid;
    }
    
    NSDictionary *parameter = @{@"dir_name":_model.sortid,@"min_id":min_id,@"page_size":@(pageSize)};
    
    [self notBusPostwithPrameter:parameter dataArr:^(NSArray *arr) {
        
        NSArray *newArr = [self getNewModel:arr withType:upPush];
        
        [self.dataArr addObjectsFromArray:newArr];
        
        [[EGOCache globalCache]setObject:self.dataArr forKey:[NSString stringWithFormat:@"%@newsList",_model.sortid]withTimeoutInterval:86400*30];
        
        [self addADtoList];
        [_tableView reloadData];
    } error:^(NSError *err) {
        
    }];
    

}

- (NSString *)getURL
{
    
    NSString *urlstr;
    if ([ISBUS boolValue]) {
        
        urlstr = [NSString stringWithFormat:@"%@/Port/newsPortInfoList",CAR_URL];
    }else{
        
        urlstr = NEWSLIST;
    }
    
    return urlstr;
}

- (void)showMessage
{
    if (!_msgLb) {
        _msgLb = [[UILabel alloc]init];
    }
    
    if (!self.tableView.tableHeaderView) {
        _msgLb.frame = CGRectMake(20, 20, WIDTH - 40, 50);
    }else{
        _msgLb.frame = CGRectMake(20, SCALEY*(179)+20, WIDTH - 40, 50);
    }

    _msgLb.text = @"暂时没有资源";
    _msgLb.textAlignment = NSTextAlignmentCenter;
    _msgLb.textColor = [UIColor lightGrayColor];
    _msgLb.font = [UIFont systemFontOfSize:18];
    [_tableView addSubview:_msgLb];
}

- (void)hideMessage
{
    [_msgLb removeFromSuperview];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NewsModel *model = [_showDataArray objectAtIndex:indexPath.row];
    UITableViewCell *cell;
    
    if ([model isKindOfClass:[NSString class]]) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"aaa"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"aaa"];
        }
        [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        if ((indexPath.row+1)%12) {
            [cell.contentView addSubview:self.bannerView2];
        }else{
            [cell.contentView addSubview:self.bannerView];
        }
        return  cell;
    }else{
    
        if (_isArticle) {
            cell = [tableView dequeueReusableCellWithIdentifier:@"ArticleListCell" forIndexPath:indexPath];
            ArticleListCell *Ncell = (ArticleListCell *)cell;
            [Ncell showModel:model];
            return cell;
        }
        
    NSArray *arr = [model.img_url componentsSeparatedByString:@"#~@"];
   
   if (arr.count >= 3 && ((NSString *)arr[2]).length) {
       
       cell = [tableView dequeueReusableCellWithIdentifier:@"ThirdImaCell" forIndexPath:indexPath];
       ThirdImaCell *Ncell = (ThirdImaCell *)cell;
       [Ncell showModel:model];
       
       return cell;

       
    }else{
        
        cell = [tableView dequeueReusableCellWithIdentifier:@"NewsListCell" forIndexPath:indexPath];
        NewsListCell *Ncell = (NewsListCell *)cell;
        [Ncell showModel:model];
        return cell;
    }
    }
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _showDataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsModel *model = [_showDataArray objectAtIndex:indexPath.row];
    
    if ([model isKindOfClass:[NSString class]]) {
    
        if (self.isFailReceive) {
            return 0;
        }else{
            return GDTMOB_AD_SUGGEST_SIZE_320x50.height+10;
        }
        
    }else{
        
        if (_isArticle) {
            return 205*SCALEX;
        }
        
        NSArray *arr = [model.img_url componentsSeparatedByString:@"#~@"];
        if (arr.count >= 3 && ((NSString *)arr[2]).length) {
            
            return 130*SCALEX;
        }
    }
    return 90*SCALEY;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsModel *model = [_showDataArray objectAtIndex:indexPath.row];
    
    if ([model isKindOfClass:[NSString class]]) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        return;
    }
    
    model.dir_name = _model.sortid;
    
    model.is_read = YES;
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    self.passModel(model);
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
       
        [[EGOCache globalCache]setObject:self.dataArr forKey:[NSString stringWithFormat:@"%@newsList",_model.sortid]withTimeoutInterval:86400*30];
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });
    });
    
    
}

-(void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    if (!self.adArr.count) {
        return;
    }
    BannerModel *model = [self.adArr objectAtIndex:index];
    
    self.myad(model);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
